import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Alert, Avatar, Badge, Col, Modal, Row, Tabs, Tag, Tooltip } from 'antd';
import React, { useRef } from 'react';

import { BlackOptions } from './logOption';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProTable from '@ant-design/pro-table';
import {
  postApiLoginRecordByIdByIndexByLimitRelatedRecords as RelatedRecords,
} from '@/services/furion-cms/loginRecord';
import { SuccessOrError } from './stateTags';
import { UserOutlined } from '@ant-design/icons';
import styles from '../index.less';
import { useIntl } from 'umi';

const { TabPane } = Tabs;

interface DetailProps {
  modalVisible: boolean;
  recored: API.LoginRecordDetailDto | undefined;
  onCancel: () => void;
  onUpdate?: () => void;
}

const DetailViewer: React.FC<DetailProps> = (props) => {
  const { modalVisible, onCancel, onUpdate, recored } = props;

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<API.LoginRecordDto>[] = [
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.loginTime',
        defaultMessage: '登录时间'
      }),
      dataIndex: 'loginTime',
      sorter: true,
      valueType: 'dateTime',
      width: 160
    },
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.host',
        defaultMessage: 'Ip地址'
      }),
      sorter: true,
      dataIndex: 'host',
      copyable: true,
      ellipsis: true,
      width: 160,
      render: (dom, entity) => {
        const { hasBlacklist, host: ipAddress } = entity;
        if (hasBlacklist) {
          return <Tooltip title={intl.formatMessage({
            id: 'pages.loginRecord.blacklist.tag',
            defaultMessage: 'Ip地址「{ipAddress}」已被加入黑名单',
          }, { ipAddress })}><Badge status="error" text={(<span style={{ display: 'inline-block' }}>{dom}</span>)} /></Tooltip>
        }
        else {
          return <Badge status="default" text={(<span style={{ display: 'inline-block' }}>{dom}</span>)} />;
        }
      }
    },
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.result',
        defaultMessage: '结果'
      }),
      dataIndex: 'result',
      ellipsis: true,
      render: (_, entity) => [
        <SuccessOrError key="loginResult" success={entity.errorMessage === ""}>
          {entity.errorMessage || intl.formatMessage({
            id: 'pages.loginRecord.result.success',
            defaultMessage: 'Login Success'
          })}
        </SuccessOrError>
      ]
    },
    {
      title: intl.formatMessage({
        id: 'pages.searchTable.titleOption',
        defaultMessage: '操作'
      }),
      dataIndex: 'option',
      valueType: 'option',
      width: 110,
      render: (_, record) => [
        <BlackOptions key="blackOption" hasBlacklist={record.hasBlacklist} ipAddress={record.host} callback={() => {
          actionRef.current?.reload();
          onUpdate?.();
        }} />
      ],
    },
  ];

  return (
    <Modal
      destroyOnClose
      title={intl.formatMessage({
        id: 'pages.common.detail',
        defaultMessage: '详情'
      })}
      visible={modalVisible}
      onCancel={onCancel}
      footer={null}
      width={700}
    >
      <Row wrap={false}>
        <Col flex="auto">
          <ProDescriptions<API.LoginRecordDetailDto>
            key="base"
            size="small"
            column={2}
            dataSource={recored}
            columns={[
              {
                dataIndex: 'result',
                span: 2,
                render: (_, entity) => [
                  <SuccessOrError key="loginResult" success={entity.errorMessage === ""}>
                    {entity.errorMessage || intl.formatMessage({
                      id: 'pages.loginRecord.result.success',
                      defaultMessage: '登录成功'
                    })}
                  </SuccessOrError>,
                  (entity.hasBlacklist && <SuccessOrError key="hasBlacklist" success={false}>
                    {intl.formatMessage({
                      id: 'pages.loginRecord.blacklist.defaultTag',
                      defaultMessage: 'Ip地址已被加入黑名单'
                    })}
                  </SuccessOrError>)
                ]
              },
              {
                title: intl.formatMessage({
                  id: 'pages.loginRecord.account',
                  defaultMessage: '账号'
                }),
                dataIndex: 'account',
              },
              {
                title: intl.formatMessage({
                  id: 'pages.loginRecord.method',
                  defaultMessage: '登录方式'
                }),
                dataIndex: 'method'
              },
              {
                title: intl.formatMessage({
                  id: 'pages.loginRecord.loginTime',
                  defaultMessage: '登录时间'
                }),
                dataIndex: 'loginTime',
                valueType: 'dateTime'
              },
              {
                title: intl.formatMessage({
                  id: 'pages.loginRecord.host',
                  defaultMessage: 'Ip地址'
                }),
                dataIndex: 'host',
              },
            ]} />
        </Col>
        <Col>
          <Row key="userBox"
            gutter={[10, 10]}
            justify="center"
            className={styles.userBox}>
            <Col span={24} className={styles.avatar}>
              {recored?.hasPassport && (<Avatar size={64} src={recored?.passportUser?.avatar} />)}
              {(!recored?.hasPassport) && (<Avatar size={64} icon={<UserOutlined />} />)}
            </Col>
            <Col span={24} className={styles.info}>
              {recored?.hasPassport && (<Tag color="#108ee9" className={styles.nickname}>{recored?.passportUser?.nickName}</Tag>)}
              {(!recored?.hasPassport) && (<Tag className={styles.nickname}>{intl.formatMessage({
                id: 'pages.loginRecord.detail.unknownUser',
                defaultMessage: '未知用户'
              })}</Tag>)}
            </Col>
          </Row>
        </Col>
      </Row>
      {recored?.innerException && (
        <Alert className={styles.innerExceptionAlert}
          message="内部异常"
          description={recored?.innerException?.message}
          type="error"
          // action={<Button size="small" type="text" icon={<MoreOutlined rotate={90} />} danger />}
          showIcon />
      )}
      <Tabs>
        <TabPane tab={intl.formatMessage({
          id: 'pages.loginRecord.detail.requestParams',
          defaultMessage: '请求参数'
        })} key="requestParams">
          <ProDescriptions
            column={1}
            layout="vertical"
            dataSource={recored}
            columns={[
              {
                title: intl.formatMessage({
                  id: 'pages.loginRecord.detail.requestParams.refererUrl',
                  defaultMessage: '请求来源'
                }),
                dataIndex: 'refererUrl',
                renderText: (val: string) => (<a href={val}>{val}</a>),
              },
              {
                title: intl.formatMessage({
                  id: 'pages.loginRecord.detail.requestParams.userAgent',
                  defaultMessage: '浏览器信息'
                }),
                dataIndex: 'userAgent',
              },
              {
                title: intl.formatMessage({
                  id: 'pages.loginRecord.detail.requestParams.postData',
                  defaultMessage: '发送数据'
                }),
                dataIndex: 'postData',
                valueType: 'jsonCode',
                renderText: (val: any) => JSON.stringify(val),
              },
            ]}
          />
        </TabPane>
        <TabPane tab={intl.formatMessage({
          id: 'pages.loginRecord.detail.relatedRecord',
          defaultMessage: '关联记录'
        })}
          forceRender={true}
          key="relatedRecords">
          <>
            <Alert className={styles.tableTopAlert} message={intl.formatMessage({
              id: 'pages.loginRecord.detail.relatedRecord.alertinfo',
              defaultMessage: '根据账号匹配到的其他记录，您可以将异常的IP地址加入到黑名单中'
            })} type="info" showIcon closable />
            <ProTable<API.LoginRecordDto>
              actionRef={actionRef}
              rowKey="id"
              params={{ id: recored?.id }}
              toolBarRender={false}
              search={false}
              scroll={{
                scrollToFirstRowOnChange: true,
                y: 235
              }}
              pagination={{
                pageSize: 10,
                showSizeChanger:true
              }}
              request={(params, sort, filter) => {
                // 表单搜索项会从 params 传入，传递给后端接口。
                console.log(params, sort, filter);
                // 转换固定的参数
                const { current, pageSize, id } = params;
                // 删除无效参数
                delete params.current;
                delete params.pageSize;
                delete params.loginTime;
                // 发起请求
                return RelatedRecords({
                  index: (current || 1),
                  limit: (pageSize || 10),
                  id
                }, sort).then(result => {
                  const { list: data, total } = result.data || {};
                  return {
                    data,
                    success: result.success,
                    total
                  }
                });
              }}
              columns={columns}
            />
          </>
        </TabPane>
      </Tabs>
    </Modal>
  )
}

export default DetailViewer;
